package com.lovo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.system.dto.SaleDto;
import com.lovo.system.dto.StockDto;
import com.lovo.system.mapper.SaleMapper;
import com.lovo.system.mapper.StockMapper;
import com.lovo.system.service.ISaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SaleServiceImpl extends ServiceImpl<SaleMapper, SaleDto> implements ISaleService {

    @Autowired
    SaleMapper saleMapper;

    @Autowired
    StockMapper stockMapper;

    @Override
    public List<SaleDto> info(int userId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        return saleMapper.selectList(qw);
    }

    @Override
    public int selectRepeat(SaleDto saleDto) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("sale_name", saleDto.getSaleName());
        qw.eq("user_id",saleDto.getUserId());
        int count = saleMapper.selectCount(qw);
        if (count == 1) {
            saleMapper.addSaleNumber(saleDto.getSaleName(),saleDto.getUserId());
            return 0;
        }
        return 1;
    }

    @Override
    public void insertSale(SaleDto saleDto) {
        saleMapper.insert(saleDto);
    }

    @Override
    public void updateSale(SaleDto saleDto) {
        saleMapper.updateById(saleDto);
    }

    @Override
    public boolean compareNumber(int number, String name) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("stock_name",name);
        StockDto stockDto = stockMapper.selectOne(qw);
        return number <= stockDto.getStockNumber();
    }

    @Override
    public String deleteSale(int id) {
        try {
            saleMapper.deleteById(id);
            return "删除成功";
        } catch (Exception e) {
            return "删除失败";
        }
    }

    @Override
    public void deleteAll(int userId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id", userId);
        saleMapper.delete(qw);
    }

}
